import CommonAction from "../../../actions/common";
import {COMMON, exportExcel, setFlowTable, setStruTable} from "../../../unit/util";

export default class DetailCommonAction extends CommonAction {
    constructor(comp) {
        super();
        this.comp = comp;
        this.struTableId = [COMMON.pageAgeEdu, COMMON.pageRankStr];
        this.flowTableId = [COMMON.pageEntryDimission, COMMON.pageStaffChange];
    }

    // 初始化
    didMount = () => {
        const {props,state} = this.comp;
        let {dispatch,staffCom} = props;
        if(staffCom.formSub){
            dispatch({
                type:'staffCom/update',
                payload:{
                    formSub:false
                }
            });
            let stateAdvObj = sessionStorage.getItem('stateAdvObj');
            stateAdvObj = JSON.parse(stateAdvObj);
            this.updateState({advObj:stateAdvObj}).then(()=>{
                // 获取数据
                this.search();
                sessionStorage.removeItem('stateAdvObj')
            })
        }else{
            this.updateState({advObj: {...state.initData}})
                .then(res => {
                    this.firstInit();
                })
                .catch(err => {
                    console.error(err)
                })
        }
    };

    // 卸载
    willUnMount = async () => {
        console.log('ddddd', this.comp.state.initData);

    };

    firstInit = async () => {
        await this.setProVal();
        // 获取数据
        this.search();
    };

    clickExport = async () => {
        const {props, action} = this.comp;
        const {page, language} = props.staffCom;
        let postData = action.cardAct.getPostData();
        let exportUrl = action.cardAct.exportUrl;
        exportExcel(postData, language, page, this.toast, exportUrl)
    };

    search = async () => {
        const {props, action} = this.comp;
        const {dispatch, staffCom} = props;
        let postData = action.cardAct.getPostData();
        postData.pageIndex && (postData.pageIndex = postData.pageIndex - 1);
        let res = await dispatch({
            type: action.cardAct.dispatchType,
            payload: {
                postData
            }
        });
        if (!res.success) return;
        if (!res.data) {
            this.toast({
                color: 'info',
                content: staffCom.language["gx6008-000194"]//未查询到数据！
            });
            this.clearTable();
            return
        }
        if (this.struTableId.includes(staffCom.page)) {
            setStruTable(res, props, this.clickTableItem).then(() => {
                this.showTable();
            });
        } else if (this.flowTableId.includes(staffCom.page)) {
            setFlowTable(res, props, this.clickTableItem).then(() => {
                this.showTable();
            });
        } else {
            this.setTable(res);
        }

    };

    setProVal = async () => {
        const {props, state: {advObj}} = this.comp;
        const {staffCom} = props;
        if (!advObj) return;
        if (staffCom.page === COMMON.pageSubdetail) return;
        // 设置组织
        if ((JSON.stringify(staffCom.hrorgobj) !== "{}")) {
            advObj.org = staffCom.hrorgobj
        }
        // 设置人员
        if ((JSON.stringify(staffCom.psncobj) !== "{}")) {
            advObj.psncl = staffCom.psncobj
        }
        // 设置时间
        // 需设置本月的详情页
        let thisMonth = [COMMON.pageEntry, COMMON.pageDimission, COMMON.pageChange];
        if (thisMonth.includes(staffCom.page)) {
            let curDate = new Date();
            let endOfMonth = new Date(curDate.getFullYear(), curDate.getMonth() + 1, 0).getDate(); // 获取本月最后一天
            let month = curDate.getMonth() + 1;
            if (month < 10) {
                month = '0' + month;
            }
            let yearMonth = curDate.getFullYear() + '-' + month;
            advObj.rangeDate = [yearMonth + '-01', yearMonth + `-${endOfMonth}`]
        }
        // 入离职趋势 和 人员变动从首页带过来的日期
        if (staffCom.mainDate.length === 4) {
            let curDate1 = new Date();
            let curDay = curDate1.getDate();
            if (curDay < 10) {
                curDay = '0' + curDay;
            }
            let month1 = curDate1.getMonth() + 1;
            if (month1 < 10) {
                month1 = '0' + month1;
            }
            advObj.rangeDate = [staffCom.mainDate + '-01-01', staffCom.mainDate + '-'+month1+'-'+curDay]
        } else if (staffCom.mainDate.length > 4) {
            let month = staffCom.mainDate + '';
            let splitStr = month.slice(4, 5);
            let monthArr = month.split(splitStr);
            let endOfMonth = new Date(monthArr[0], monthArr[1], 0).getDate(); // 获取本月最后一天
            advObj.rangeDate = [staffCom.mainDate + '-01', staffCom.mainDate + `-${endOfMonth}`]
        }
        await this.updateState({advObj})
    };

    showTable = () => {
        if (this.comp.state.showTable) return;
        this.updateState({
            showTable: true
        })
    };

    setTable = (res) => {
        const {props} = this.comp;
        const {staffCom} = props;
        let tableId = COMMON.tableIdObj[staffCom.page];
        if (staffCom.page === COMMON.pageSubdetail) {
            tableId = staffCom.advObj.tableId;
        }
        if (!res.data[tableId]) return;
        props.editTable.setTableData(tableId, {rows: res.data[tableId].rows}, false);
        let pageInfo = res.data[tableId].pageInfo;
        pageInfo.pageIndex = (pageInfo.pageIndex - 0) + 1;
        this.updateState({pageInfo});
    };

    clearTable = () => {
        const {props} = this.comp;
        const {staffCom} = props;
        let tableId = COMMON.tableIdObj[staffCom.page];
        this.updateState({pageInfo: COMMON.pageInfo});
        props.editTable.setTableData(tableId, {rows: []});
    };

    clickTableItem = async (record, key) => {
        const {props, action,state} = this.comp;
        const {dispatch, staffCom} = props;
        let values = record.values[key].values;
        if (values.count === "0") return;
        let postData = action.cardAct.getPostData();
        let stateAdvObj = JSON.stringify(state.advObj);
        sessionStorage.setItem('stateAdvObj',stateAdvObj);
        let advObj = {
            pk_org: (record.values.org_id && record.values.org_id.value) || postData.pk_org||'',
            pk_psncl: postData.pk_psncl,  // 人员类别
            pk_age: '',
            pk_edu: '',
            pk_jobrank: '',
            includesub: values.includesub || false,
            istotal: '',
            lastPage: staffCom.page,


            totaltype: '',
            psncode: '', // 人员编码
            pk_majorcorp: '', // 合同主体单位主键
            begindate: '',
            enddate: ''
        };
        if (record.values.month) {
            let month = record.values.month.value;
            let splitStr = month.slice(4, 5);
            let monthArr = month.split(splitStr);
            let endOfMonth = new Date(monthArr[0], monthArr[1], 0).getDate(); // 获取本月最后一天
            advObj.begindate = month + '-01';
            advObj.enddate = month + `-${endOfMonth}`;
        }
        if (values.key === 'ageall') {
            advObj.pk_age = values.id || '';
            advObj.istotal = !values.id;
            advObj.totaltype = advObj.istotal && "age" || '';
            advObj.tableId = COMMON.tableIdObj.totle;
        }
        if (values.key === 'eduall') {
            advObj.pk_edu = values.id || '';
            advObj.istotal = !values.id;
            advObj.totaltype = advObj.istotal && "edu" || '';
            advObj.tableId = COMMON.tableIdObj.totle;
        }
        if (values.key === 'jobrankall') {
            advObj.pk_jobrank = values.id || '';
            advObj.istotal = !values.id;
            advObj.totaltype = advObj.istotal && "jobrank" || '';
            advObj.tableId = COMMON.tableIdObj.totle;
        }
        if (values.key === 'changeall') {
            advObj.pk_trnstype = values.type_id;
            advObj.tableId = COMMON.tableIdObj.change;
        }
        if (values.key === 'dimissionall') {
            advObj.pk_trnstype = values.type_id;
            advObj.tableId = COMMON.tableIdObj.dimission;
        }
        if (values.key === 'entryall') {
            advObj.pk_trnstype = values.type_id;
            advObj.tableId = COMMON.tableIdObj.entry;
        }
        let res = await dispatch({
            type: "staffCom/update",
            payload: {
                page: COMMON.pageSubdetail,
                advObj
            }
        });
    };

    clear = () => {
        const {action} = this.comp;
        action.cardAct.clear();
    };

    referChange = (key, val) => {
        let advObj = this.comp.state.advObj;
        if (typeof key === 'string') {
            Object.assign(advObj, {
                [key]: val
            });
        } else if (Array.isArray(key)) {
            key.forEach(item => {
                for (let a in item) {
                    Object.assign(advObj, {
                        [a]: item[a]
                    });
                }
            })
        }

        this.updateState(advObj)
    };

    searchValChange = (searchVal) => {
        this.updateState({searchVal});
    };

    updateState = (obj) => {
        return new Promise(resolve => {
            this.comp.setState(obj, resolve);
        })
    }
}